package groovy.jmx.builder

import groovy.jmx.builder.modelmbean.ModelMBeanBuilder
import groovy.jmx.builder.node.MBeanNodeData
import javax.management.ObjectName
import javax.management.modelmbean.RequiredModelMBean




class JmxMBeanFactory extends AbstractFactory {
    MBeanNodeData data;
    ModelMBeanBuilder mBeanBuilder = new ModelMBeanBuilder()

    public Object newInstance(FactoryBuilderSupport builder, Object nodeName, Object nodeArgs, Map nodeAttribs) {
        if (nodeArgs) {
            data = new MBeanNodeData(object: nodeArgs)
        } else if (nodeAttribs) {
            data = new MBeanNodeData(nodeAttribs)
        } else
            throw new JmxBuilderException("You must provide reference of object expose as JMX MBean. ")

        return data
    }

    public boolean onHandleNodeAttributes(FactoryBuilderSupport builder, Object node, Map nodeAttribs) {
        return true;
    }

    public void onNodeCompleted(FactoryBuilderSupport builder, Object parentNode, Object childNode) {
        if (childNode && childNode instanceof MBeanNodeData) {
            RequiredModelMBean bean = mBeanBuilder.build(childNode)
            parentNode.registerMBean(bean, new ObjectName(childNode.name))
        }
    }

    public boolean isLeaf() {
        return false
    }
}
